package com.junxonline.instant.terminal.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.reflect.TypeToken;
import com.junxonline.instant.common.constant.TerminalCommandMqConstant;
import com.junxonline.instant.common.util.terminal.NettyChannelUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

/**
 * RocketMq设置指令消费者
 *
 * @author JunX
 * @date 2022-05-26
 */
@Log4j2
@Component
@Transactional
@RocketMQMessageListener(consumerGroup = TerminalCommandMqConstant.GROUP_SET_COMMAND, topic = TerminalCommandMqConstant.TOPIC_SET_COMMAND)
public class TerminalSetCommandListener implements RocketMQListener<MessageExt> {

    /**
     * 消息解析与发送
     *
     * @param message 消息内容
     */
    @Override
    public void onMessage(MessageExt message) {
        String topic = message.getTopic();
        String tags = message.getTags();
        String body = new String(message.getBody());
        // 解析
        HashMap<String, Object> data = JSON.parseObject(body, new TypeToken<HashMap<String, Object>>() {
        }.getType());
        log.info("TerminalSetCommandListener接收到消息 -> topic={}, tags={}, 消息内容={}", topic, tags, body);
        if (data != null) {

            String terminalCode = (String) data.get("terminalCode");
            JSONObject msg = (JSONObject) data.get("msg");
            // 判断客户端是否在线
            if (StrUtil.isNotBlank(terminalCode) && NettyChannelUtils.hasChannel(terminalCode)) {
                // 在线的客户端直接发送消息
                NettyChannelUtils.sendSingleMessage(terminalCode, msg.toJSONString());
                log.info("向终端[" + terminalCode + "]发送了一条消息 -> " + msg.toJSONString());
                // 客户端不在线
            } else {
                log.warn("向终端[" + terminalCode + "]发送消息失败 原因 -> 设备不在线");
            }
        }
    }
}
